<template>
  <div class="taskList">
    <div class="mains_contain">
      <el-form :inline="true" :model="searchForm" size="small">
        <el-form-item label="租户">
          <el-select v-model="searchForm.tenantId" clearable style="width: 100%" placeholder="请选择">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务名称">
          <el-input v-model="searchForm.taskName" clearable placeholder="请输入任务名称" />
        </el-form-item>
        <!-- <el-form-item label="节点类型">
          <el-select v-model="searchForm.nodeType" clearable placeholder="请选择节点类型">
            <el-option label="终端设备" value="ENDPOINT"></el-option>
            <el-option label="网关设备" value="GATEWAY"></el-option>
            <el-option label="未知设备" value="UNKNOW"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item>
          <el-button type="primary" @click="search" size="mini">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onAdd" size="mini" v-has="['task:add']">创建任务</el-button>
        </el-form-item>
      </el-form>
      <div class="contant">
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row
          :header-cell-style="{ background: '#e5e5e5', color: '#000' }">
          <!-- <el-table-column type="selection" width="40" /> -->
          <el-table-column prop="taskName" label="任务名称" align="center" />
          <el-table-column prop="tenantTxt" label="租户" align="center" />
          <el-table-column prop="taskType" label="任务类型" align="center">
            <template slot-scope="{ row }">
              <span style="color:#409eff">{{  row.taskType | getTypeName(typeList) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="taskStatus" label="任务状态" align="center">
            <template slot-scope="{ row }">
              <span style="color:#F56C6C" v-if="row.taskStatus == 'created'">未执行</span>
              <span style="color:#67C23A" v-if="row.taskStatus == 'issued'">已执行</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" min-width="150">
            <template slot-scope="scope">
              {{ scope.row.createTime | formatTime }}
            </template>
          </el-table-column>
          <el-table-column prop="taskRemark" label="描述" align="center" />
          <el-table-column label="操作" width="350" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="mini" v-has="['task:start']" icon="el-icon-coin" :disabled="scope.row.taskStatus != 'created'" @click="handleStart(scope.row)">任务开启</el-button>
              <el-button type="text" size="mini" v-has="['task:edit']" icon="el-icon-edit" :disabled="scope.row.taskStatus != 'created'" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="mini" v-has="['task:delete']" icon="el-icon-delete" :disabled="scope.row.taskStatus != 'created'" @click="handleDelete(scope.row)"
                :style="{color:scope.row.taskStatus != 'created'?'':'#F56C6C'}">删除</el-button>
              <el-button type="text" size="mini" icon="el-icon-view" :disabled="scope.row.taskStatus != 'issued'" @click="handleSee(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right">
          <pagination v-show="pagination.total > 0" :limit.sync="pagination.pageSize" :page.sync="pagination.page" :total="pagination.total" @pagination="getPageList" />
        </div>
      </div>
    </div>
    <el-dialog :title="cirTitle" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="100px" size="small" :rules="rules">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" clearable />
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-select v-model="form.taskType" placeholder="请选择任务类型" style="width: 100%" clearable>
            <el-option label="整包升级" value="packageUpgrade"></el-option>
            <el-option label="差分升级" value="differentialUpgrade"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务优先级" prop="taskPriority">
          <el-input v-model.number="form.taskPriority" clearable placeholder="请任务优先级(数字越小优先级越高)" />
        </el-form-item>
        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="form.tenantId" style="width: 100%" placeholder="请选择">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="taskRemark">
          <el-input type="textarea" v-model="form.taskRemark" clearable />
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="primary" @click="submitForm('form')" size="small">保存</el-button>
        <el-button @click="dialogVisible = false" size="small">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import * as api from "@/api/link/task";
import * as tenantApi from "@/api/sys/tenant";

export default {
  comments: {},
  props: {},
  data() {
    return {
      tenantList: [],
      type: "",
      searchForm: { },
      multipleSelection: [],
      tableData: [],
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
      cirTitle: "新增任务",
      dialogVisible: false,
      rules: {
        taskName: [
          { required: true, message: "必须输入名称", trigger: "blur" },
        ],
        taskType: [
          { required: true, message: "必须选择任务类型", trigger: "change" },
        ],
        taskPriority: [
          { required: true, message: "必须输入任务优先级", trigger: "blur" },
        ],
        tenantId: [
          { required: true, message: "必须选择租户", trigger: "change" },
        ],
      },
      form: {},
      typeList: [
        // { value: 1, label: "获取设备信息" },
        // { value: 2, label: "系统文件下载" },
        // { value: 3, label: "系统文件下载状态查询" },
        { value: "DeviceState", label: "获取设备信息" },
        { value: "SoftwareLoad", label: "设备升级" },
        { value: "PatchLoad", label: "补丁升级" },
        { value: "SoftwareLoadStatus", label: "系统文件下载状态查询" },
        { value: "CfgfileLoad", label: "配置文件升级" },
        { value: "CfgfileLoadStatus", label: "配置文件升级状态查询" },
        { value: "SystemReboot", label: "重启设备" },
        { value: "LogfileUpload", label: "设备日志收集" },
        { value: "LogfileUploadNotify", label: "设备日志收集结果上报" },
        { value: "LogfileUploadStatus", label: "设备日志收集状态查询" },
        { value: "ShellScriptLoad", label: "应用升级" },
        { value: "ShellScriptLoadNotify", label: "可执行文件执行结果上报" },
        { value: "ShellScriptLoadStatus", label: "可执行文件执行状态查询" },
        { value: "EthStatus", label: "网络接口信息查询" },
      ],
    };
  },
  filters: {
    getTypeName(val, list) {
      var typeName = "";
      if (!val) {
        typeName = "";
      }
      list.map((item) => {
        if (val == item.value) {
          typeName = item.label;
        }
      });
      return typeName;
    },
  },
  computed: {
    maxHeight() {
      var curHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      return curHeight - 280;
    },
  },
  created() {
    this.getTenantList();
    let f = localStorage.getItem('taskForms')
    if (f) {
      this.searchForm = JSON.parse(f)
      this.pagination.pageSize = this.searchForm.pageSize
      this.pagination.page = this.searchForm.page
      this.pagination.current = this.searchForm.current
      this.pagination.total = this.searchForm.total
      this.getPageList();
    } else {
      this.getPageList();
    }
  },
  mounted() { },
  beforeRouteLeave(to, from, next) {
    if (to.name == 'taskOverview') {
      let form = this.searchForm
      localStorage.setItem('taskForms', JSON.stringify(form))
      next()
    } else {
      let f = localStorage.getItem('taskForms')
      if (f) {
        localStorage.removeItem('taskForms')
      }
      next()
    }
  },
  methods: {
    // 获取租户数据
    getTenantList() {
      tenantApi.queryIdNamePair().then((res) => {
        this.tenantList = res.data;
      });
    },
    // 复选框事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getPageList() {
      this.searchList();
    },
    search() {
      this.pagination.page = 1;
      this.searchList();
    },
    searchList() {
      const p = Object.assign(this.searchForm, this.pagination);
      if (p.taskName) {
        p.taskName = p.taskName.replace(/\s*/g, ""); // 去除任务名称中的空格
      }
      api.page(p).then((resp) => {
        this.tableData = resp.data.list;
        this.pagination = resp.data.pagination;
        this.pagination.page = resp.data.pagination.current;
      });
    },
    onAdd() {
      // this.form = {}
      // this.cirTitle = '新增任务'
      // this.dialogVisible = true
      this.$router.push({
        path: "/taskDispatchAdd",
      });
    },
    handleStart(row) {
      this.$confirm("是否下发命令?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        api.commandIssue(row.id).then((resp) => {
          if (resp.code == 200) {
            this.$message({
              type: "success",
              message: "下发成功!",
            });
            this.search();
          }
        });
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var p = Object.assign(this.form);
          switch (this.cirTitle) {
            case "新增任务":
              api.save(p).then((resp) => {
                this.$message({
                  type: "success",
                  message: "新增成功!",
                });
                this.dialogVisible = false;
                this.search();
              });
              break;
            case "编辑任务":
              api.update(p).then((resp) => {
                this.$message({
                  type: "success",
                  message: "编辑成功!",
                });
                this.dialogVisible = false;
                this.search();
              });
              break;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleEdit(row) {
      console.log(row)
      // this.cirTitle = '编辑任务'
      // this.form = Object.assign(row)
      // this.dialogVisible = true
      this.$router.push({
        path: "/taskDispatchEdit",
        query: {
          id: row.id
        },
      });
    },
    handleDelete(row) {
      this.$confirm("此操作将删除该任务, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.deleteById(row.id).then((resp) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.search();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSee(row) {
      api.getById(row.id).then((res) => {
        if (res.code == 200) {
          this.$router.push({
            path: "/taskOverview",
            query: res.data,
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.taskList {
  padding: 20px;
}
.fileUpload {
  padding: 20px;

  .curHeader {
    position: relative;
    height: 40px;
    .searcherBox {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
}
</style>
